package controllers;

import controllers.common.ControllerBase;
import dao.common.CategoryManager;
import dao.common.ImageManager;
import dao.hibernate.CategoryManagerHB;
import dao.hibernate.ImageManagerHB;
import models.entities.CategoryEntity;
import models.exceptions.CreateEntityException;
import models.helpers.ImageHelper;
import models.repository.CategoryRepositorySQL;
import models.repository.common.CategoryRepository;
import play.Play;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.List;

public class Category extends ControllerBase {

    private static CategoryRepository repository = new CategoryRepositorySQL();
    private static CategoryManager categoryManager = new CategoryManagerHB();
    private static ImageManager imageManager = new ImageManagerHB();
    
    public static void create(CategoryEntity category) throws CreateEntityException, IOException {
        repository.create(category);
        render();
    }

    public static void list(int id) throws IOException {
        List<models.shop.Category> categories = categoryManager.listByParentId(id, true);
        models.shop.Category cat = categoryManager.getById(id);
        render(categories, cat);
    }

    public static void getImage(int imageId, int height, int width) throws IOException {
        models.shop.Image image = imageManager.getById(imageId);
        InputStream productImage = ImageHelper.getImage(Play.getFile("data").toString(), image, width, height, "categories", true);
        setCache(1000000);
        renderBinary(productImage, MessageFormat.format("{0}_{1}x{2}.jpg", image.md5, width, height), "image/jpg", true);
    }
}
